package com.tyt.lelan;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.tyt.lelan.adapter.EntryAdapter;
import com.tyt.lelan.adapter.RssItemAdapter;
import com.tyt.lelan.entity.RssItem;
import com.tyt.lelan.provider.FeedsData;
import com.tyt.lelan.provider.FeedsData.AllFeedsColumns;
import com.tyt.lelan.provider.FeedsData.EntryColumns;
import com.tyt.lelan.provider.FeedsData.MyFeedsColumns;
import com.tyt.lelan.utils.PubDateParser;
import com.tyt.lelan.utils.RssParser;
import com.tyt.lelan.view.ScrollLayout;

public class RssItemListActivity extends Activity implements OnClickListener, OnItemClickListener{

	private String basePubData;
	private int    rss_id;

	private Bundle mData;
	private Boolean isOnline;

	private RssParser mParser;
	private ScrollLayout mFeedView;
	private ProgressBar mProgressBar;	
	private ArrayList<RssItem> data ;
	private final int PAGE_SIZE_RSSLIST=8;

	private final int ENTRY_REFRESH=0;
	private final int ENTRY_LOAD=1;
	private final int ADD_FEED=2;

	private final int DIALOG_ADDFEED=0;

	public void onCreate(Bundle savedInstanceState){

		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_rsslist);


		mFeedView=(ScrollLayout) findViewById(R.id.scroll_rsslist_feedView);
		mProgressBar=(ProgressBar) findViewById(R.id.progress_rssllist);
		(findViewById(R.id.btn_rsslist_back)).setOnClickListener(this);

		initialView();

	}

	private void initialView(){

		mData=getIntent().getExtras();
		if(mData!=null){	
			rss_id=mData.getInt("id");
			isOnline = mData.getBoolean("online", false);
			String link = mData.getString("link");
			((TextView)findViewById(R.id.tv_rsslist_title))	.setText(mData.getString("category")+"-"+mData.getString("name"));
			if(isOnline) {
				mParser = new RssParser(link);
				mProgressBar.setVisibility(View.VISIBLE);
				handler.post(fetchRunnable);
			} else {

				Cursor cursor=managedQuery(EntryColumns.CONTENT_URI,null,EntryColumns.RSS_ID+"="+rss_id , null, EntryColumns.PUBDATE+" DESC");
				//若数据库中已有数据，则先显示
				if(0!=cursor.getCount()){
					cursor.moveToNext();
					basePubData=cursor.getString(cursor.getColumnIndex(EntryColumns.PUBDATE));
					Log.i("=BasePubData=", basePubData);
					setRssListView(false);
				}	
				else{
					basePubData=null;
				}
				mParser=new RssParser(mData.getString("link"),RssItemListActivity.this, PubDateParser.parse(basePubData),rss_id);		     
				new RssParserload().execute();
				cursor.close();
			}

		}



	}

	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch(id){
		case DIALOG_ADDFEED:
			final Dialog mAddFeedDialog = new Dialog(this);
			View addFeedDv = LayoutInflater.from(this).inflate(R.layout.dialog_addfeed, null);
			addFeedDv.findViewById(R.id.btn_addFeedok).setOnClickListener(this);
			addFeedDv.findViewById(R.id.btn_addFeedcancel).setOnClickListener(this);
			((TextView)addFeedDv.findViewById(R.id.tv_addFeed)).setText("添加订阅\n"+mData.getString("name"));
			//				addFeedDv.setOnClickListener(this);
			mAddFeedDialog.setContentView(addFeedDv);
			return mAddFeedDialog;

		}
		return null;
	}

	private Handler handler = new Handler() 
	{
		@Override
		public void handleMessage(Message msg) 
		{

			Bundle data=msg.getData();
			switch (msg.what){
			case ENTRY_LOAD:
				mProgressBar.setVisibility(View.INVISIBLE);
				setRssListView(data.getBoolean("isOnline"));
				break;
			case ADD_FEED:
				ContentValues values=new ContentValues();

				String category=data.getString("category");
				String name=data.getString("name");
				String link=data.getString("link");
				String icon_name= data.getString("icon_name");
				int id=data.getInt("id");

				//将此订阅添加到我的订阅表中
				values.put(MyFeedsColumns.CATEGORY,category);
				values.put(FeedsData.NAME, name);
				values.put(MyFeedsColumns.LINK, link);
				values.put(MyFeedsColumns.ICON_NAME, icon_name);
				values.put(MyFeedsColumns.RSS_ID, id);
				RssItemListActivity.this.getContentResolver().insert(MyFeedsColumns.CONTENT_URI, values);

				//在总订阅表中标记此表为已订阅
				ContentValues values_forall=new ContentValues();
				values_forall.put(AllFeedsColumns.SELECTED, "1");
				values_forall.put(AllFeedsColumns.CATEGORY, category);
				values_forall.put(AllFeedsColumns.CATEGORY,category);
				values_forall.put(FeedsData.NAME, name);
				values_forall.put(AllFeedsColumns.LINK, link);
				values_forall.put(AllFeedsColumns.ICON_NAME, icon_name);
				RssItemListActivity.this.getContentResolver().update(AllFeedsColumns.CONTENT_URI, values_forall,AllFeedsColumns._ID+"="+id , null);
				Toast.makeText(RssItemListActivity.this, "添加"+data.getString("name"), Toast.LENGTH_SHORT).show();

				break;
			default:
				break;
			}
		}
	};


	private Runnable fetchRunnable = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				data =mParser.parserNotStore();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.i("", e.toString());
			}
			Message msg=new Message();
			msg.what=ENTRY_LOAD;
			Bundle b= new Bundle();
			b.putBoolean("isOnline", true);
			msg.setData(b);
			handler.sendMessage(msg);
		}

	};

	private class RssParserload extends AsyncTask<String,Integer,Void>{

		private boolean isUpdate;

		@Override
		protected void onPreExecute() {

			mProgressBar.setVisibility(View.VISIBLE);
			super.onPreExecute();

		}


		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub

			try {
				isUpdate=mParser.parser();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		protected void onPostExecute(Void result) {

			if(isUpdate){
				Message msg=new Message();
				msg.what=ENTRY_LOAD;
				Bundle b= new Bundle();
				b.putBoolean("isOnline", false);
				msg.setData(b);
				handler.sendMessage(msg);

			}
			mProgressBar.setVisibility(View.GONE);
			super.onPostExecute(result);
		}

	}

	public void setRssListView(Boolean b){

		mFeedView.removeAllViews();
		if(b){
			int dataSize=data.size();
			if(0!=dataSize){

				int pageCount=1+data.size()/PAGE_SIZE_RSSLIST;

				for(int i=0;i<pageCount;i++){

					GridView gv=new GridView(RssItemListActivity.this);
					gv.setNumColumns(2);
					gv.setAdapter(new RssItemAdapter(this,data,i));   

					mFeedView.addView(gv);		        
				}
			}
		}else{

			Cursor cursor=managedQuery(EntryColumns.CONTENT_URI,null,EntryColumns.RSS_ID+"="+rss_id , null, null);
			int dataSize=cursor.getCount();
			if(0!=dataSize){

				int pageCount=1+dataSize/PAGE_SIZE_RSSLIST;

				for(int i=0;i<pageCount;i++){

					GridView gv=new GridView(RssItemListActivity.this);
					gv.setNumColumns(2);
					gv.setPadding(2, 2, 0,2);
					gv.setVerticalScrollBarEnabled(false);
					gv.setAdapter(new EntryAdapter(RssItemListActivity.this,R.layout.item_rssitem,cursor,i));   
					gv.setOnItemClickListener(this);
					mFeedView.addView(gv);		        
				}
			}
		}
	}
	 
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Message msg=new Message();
		Bundle data=new Bundle();
		switch (v.getId()){
		case R.id.btn_rsslist_back:
			int selected=mData.getInt("selected",-1);
			selected=(-1==selected)?1:selected;			
			if(0==selected){			
				showDialog(DIALOG_ADDFEED);			
			}
			else{
				this.finish();
			}

			break;
		case R.id.btn_addFeedok:

			data=mData;
			msg.what=ADD_FEED;
			msg.setData(data);
			handler.sendMessage(msg);
			RssItemListActivity.this.finish();

			break;
		case R.id.btn_addFeedcancel:

			dismissDialog(DIALOG_ADDFEED);
			RssItemListActivity.this.finish();
			break;
		default:
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		Intent i=new Intent();
		Bundle data=new Bundle();
		i.setClass(this, WebAcitivty.class);
		if(isOnline){
			RssItem item =  (RssItem) parent.getAdapter().getItem(position);
			data.putString("link", item.getLink());
			data.putString("title", item.getTitle());
			data.putString("description", item.getDescription());
		}else{
			Cursor cursor = (Cursor) parent.getAdapter().getItem(position);
			data.putInt("id", cursor.getInt(cursor.getColumnIndex(FeedsData.EntryColumns._ID)));
			data.putInt("title", cursor.getInt(cursor.getColumnIndex(FeedsData.EntryColumns.TITLE)));
			data.putString("link", cursor.getString(cursor.getColumnIndex(FeedsData.EntryColumns.LINK)));
			data.putString("description", cursor.getString(cursor.getColumnIndex(FeedsData.EntryColumns.DESCRIPTION)));
		}
		i.putExtras(data);
		startActivity(i);
	}

}
